<!--
 * Copyright 2019 ia-cloud project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 -->

<script type="text/html" data-template-name="HMI-Schneider-AE">

  <!-- HMI Schneider node（設定Node）の選択-->
  <div class="form-row" id="com-block">
    <label for="node-input-HmiSchneiderCom" style= "vertical-align: middle;">
      <span data-i18n="editor.hmiSchneiderNode"></span><span style="color: #ff0000;">*</span>
    </label>
    <input type="text" style="width: 300px" id="node-input-HmiSchneiderCom">
  </div>
  
  <!-- 隠しのNodeプロパティ -->
  <div class="form-row" hidden>
    <input type="text" id="node-input-configReady">
  </div>
  
  <!-- Tab, ownself -->
  <div class="form-row">
    <ul style="min-width: 500px; margin-bottom: 20px;" id="red-tabs">
    </ul>
  </div>
  <!-- Tab contents -->
  <div id="tabs-content" style="min-height:250px;">

    <!-- tab-object-properties starts -->
    <div id="tab-object-property">

      <div class="form-row">
        <label style="width:150px;" for="node-input-storeInterval">
          <span data-i18n="editor.period"></span>
        </label>
        <input type="number" id="node-input-storeInterval" min="0" step="1" value="0" style="display: inline-block; width: 120px;">
        <label for="node-input-storeAsync" style="margin-left: 20px;"><span data-i18n="editor.async"></span></label>
        <input type="checkbox" id="node-input-storeAsync" style="display: inline-block; width: auto;" >
      </div>
      <div class="form-row">
        <label style="width:150px;" for="node-input-objectKey">
          <span data-i18n="editor.objectKey"></span>
          <span style="color: #ff0000;">*</span>
        </label>
        <input required="required" class="form-control" type="text" style="width: 300px" id="node-input-objectKey" data-i18n="[placeholder]editor.objectKeyholder">
      </div>
      <div class="form-row">
        <label style="width:150px;" for="node-input-objectdescription">
          <span data-i18n="editor.objectDescription"></span>
        </label>
        <input type="text" style="width: 300px" id="node-input-objectDescription" data-i18n="[placeholder]editor.objectDescription">
      </div>
    </div>
    
    <!-- tab aeItem-property starts -->
    <div id="tab-aeItem-property">
      <!-- aeItem propertyの設定 -->
      <div class="form-row">
        <label for="node-input-contentType"><i class="fa fa-tag"></i>
          <span data-i18n="editor.contentType"></span>
        </label>
        <input type="text" id="node-input-contentType" disabled="disabled">
      </div>
      <div class="form-row node-input-aeItemcontainer-row">
        <ol id="node-input-aeItemcontainer"></ol>
      </div>
    </div>
  </div>

  <div class="form-row" id = name-block>
    <hr>
    <label for="node-input-name" ><i class="fa fa-tag"></i><span data-i18n="editor.name"></span></label>
    <input type="text" class="form-control" id="node-input-name" data-i18n="[placeholder]editor.name">
  </div>
  
</script>

<script type="text/javascript">

  RED.nodes.registerType('HMI-Schneider-AE',{
    category: 'iaCloud devices',
    color:"rgb(231, 180, 100)",
    defaults: {
      // node properties
      name: {value:""},
      HmiSchneiderCom: {value:"", type:"HMI-Schneider-com", required: true},
      // object properties
      storeInterval: {value:"0"},
      storeAsync: {value:true},
      objectKey: {value:"", required: true},
      objectDescription: {value:""},
      // aeItems property
      contentType: {value:"Alarm&Event"},
      aeItems: {value:[{}]},
      // 必須項目が揃っているかのflag、Nodeに赤三角を表示するために必要
      configReady: {value: "", required: true}
    },
    inputs:1,
    outputs:1,
    icon: "ia-cloud.png",  //アイコンはTBD
    label: function() {
      return this.name||this._("editor.paletteLabel");
    },
    labelStyle: function() {
      return this.name?"node_label_italic":"";
    },
    paletteLabel: function() {
        return this._("editor.paletteLabel") || "HMISchneider-AE";
    },
    oneditprepare: function() {
      const node = this;
      // Locale strings
      const labelVarName = node._("editor.varName");
      const labelAECode = node._("editor.AECode");
      const labelAEDescription = node._("editor.AEDescription");
      
      // editableList item のhtml要素
      const itemVarCode =`
        <label style="width:80px; display:inline-block; text-align:left;">${labelVarName}</label>
        <input required="required" type="text" style="display:inline-block; text-align:left; width:100px;" class="varName" placeholder="${labelVarName}">
        <label style="width:80px; display:inline-block; margin-left:20px; text-align:left;">${labelAECode}</label>
        <input type="text" style="display:inline-block; text-align:left; width:80px;" class="code" placeholder="${labelAECode}">
      `;
      const itemDescription =`
        <span style="display:inline-block; width:30px"> </span>
        <label style="width:80px; display:inline-block; text-align:left;">${labelAEDescription}</label>
        <input type="text" style="width: 250px" class="description" placeholder="${labelAEDescription}">
      `;
      
      // Tab
      const tabs = RED.tabs.create({
        id: 'red-tabs',
        onchange(tab) {
          $('#tabs-content').children().hide();
          $("#" + tab.id).show();
          $("#red-tabs").resize();
      },
      });
      tabs.addTab({
          id: 'tab-object-property',
          label: this._('editor.tab.object-settings'),
      });
      tabs.addTab({
          id: 'tab-aeItem-property',
          label: this._('editor.tab.data-settings'),
      });

      // Define editableList.
      $('#node-input-aeItemcontainer').css('min-height', '150px').css('min-width', '450px').editableList({
        removable: true,
        sortable: true,
        height: 500,
        
        // Process when click add button.
        addItem: function(container, index, aeItem) {
          let div1 = $('<div></div>').appendTo(container);
          let div2 = $('<div></div>',{style:"margin-top:8px;"}).appendTo(container);

          // 追加ボタンが押されたら、aeItemは 空{} で呼ばれます。
          if(!Object.keys(aeItem).length) {
            aeItem = {
              varName:"",
              code:"",
              description:""
            };
          };
         
          $('<span></span>', {class:"index", style:"display:inline-block;text-align:right; width:30px; padding-right:5px;"})
            .text((index + 1) + " :")
            .appendTo(div1);
          $(itemVarCode).appendTo(div1);
          $(itemDescription).appendTo(div2);
          
          div1.find(".varName").val(aeItem.varName);
          div1.find(".code").val(aeItem.code);
          div2.find(".description").val(aeItem.description);
        },
        
        // リストの順番が変わったら呼ばれる。
        sortItems: function(items) {
          items.each(function(i, elm){
            // 番号を降り直し
            elm.find(".index").text((i + 1) + ":");
          });
        },
        
        // リストの項目が削除されたら呼ばれる。
        removeItem: function(aeItem){
          let items = $('#node-input-aeItemcontainer').editableList("items");
          items.each(function(i, elm){
            // 番号を降り直し
            elm.find(".index").text((i + 1) + ":");
          });
        }
      });

      // Nodeの設定パラメータを取り出し、editableListに登録
      for (let i=0; i<node.aeItems.length; i++) {
        $("#node-input-aeItemcontainer").editableList('addItem',node.aeItems[i]);
      }
    },

    oneditsave: function() {
      const node = this;
      let configReady = "ready";
      let items = $("#node-input-aeItemcontainer").editableList('items');

      // データ設定を作成
      node.aeItems = [];
      
      items.each(function(i, elm){
        let item = {
          varName: elm.find(".varName").val(),
          code: elm.find(".code").val(),
          description: elm.find(".description").val()
          }
        
        // 必須propertyが揃っているか？
        if (!item.varName) configReady = "";
        
        node.aeItems.push(item);
      });
      
      // objectKeyはある？
      if (!$("#node-input-objectKey").val()) configReady = "";
      // データ設定が一つはある？
      if (!node.aeItems.length) configReady = "";

      // 設定完了フラグをセット
      $("#node-input-configReady").val(configReady);
    },

    oneditresize: function(size) {
      if ($("#tab-aeItem-property").is(":visible")) {
        // エディタがリサイズされたら
        let height = size.height;
        // Tab以外の部分の高さを引く
        height -= $("#com-block").outerHeight(true);
        height -= $("#name-block").outerHeight(true);
        // aeItemプロパティTab内の、editableList以外の行の高さを引く
        rows = $("#tab-aeItem-property>div:not(.node-input-aeItemcontainer-row)");
        for (let i=0; i<rows.length; i++) {
          height -= $(rows[i]).outerHeight(true);
        }        
        // タブの部分の高さ（大体）
        height -= 60;

        // editableListのマージンを引く
        const editorRow = $("#tab-aeItem-property>div.node-input-aeItemcontainer-row");
        height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom")));


        // editableListの高さを設定。editableListが非表示の時は正しく動作しない。
        $("#node-input-aeItemcontainer").editableList('height',height);
      }
    }
  });

</script>
